package com.qyhl.module_practice.team.list;

import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.gyf.immersionbar.ImmersionBar;
import com.qyhl.module_practice.R;
import com.qyhl.module_practice.R2;
import com.qyhl.webtv.basiclib.base.BaseFragment;
import com.qyhl.webtv.basiclib.utils.DateUtils;
import com.qyhl.webtv.basiclib.utils.NetUtil;
import com.qyhl.webtv.basiclib.utils.StringUtils;
import com.qyhl.webtv.commonlib.common.CommonUtils;
import com.qyhl.webtv.commonlib.constant.ARouterPathConstant;
import com.qyhl.webtv.commonlib.entity.civilized.PracticeIsVolunteerBean;
import com.qyhl.webtv.commonlib.entity.civilized.PracticeTeamBean;
import com.qyhl.webtv.commonlib.service.UserService;
import com.qyhl.webtv.commonlib.utils.eventbus.BusFactory;
import com.qyhl.webtv.commonlib.utils.eventbus.Event;
import com.qyhl.webtv.commonlib.utils.router.RouterManager;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.weavey.loading.lib.LoadingLayout;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.MultiItemTypeAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class PracticeTeamListFragment extends BaseFragment implements PracticeTeamListContract.PracticeTeamListView {
    @BindView(R2.id.bottom_layout)
    LinearLayout bottomLayout;
    @BindView(R2.id.recycle_view)
    RecyclerView recycleView;
    @BindView(R2.id.refresh)
    SmartRefreshLayout refresh;
    @BindView(R2.id.load_mask)
    LoadingLayout loadMask;
    @BindView(R2.id.search_btn)
    TextView searchBtn;
    @BindView(R2.id.search_txt)
    TextView searchTxt;
    @BindView(R2.id.search_layout)
    RelativeLayout searchLayout;


    private PracticeTeamListPresenter mPresenter;

    private CommonAdapter commonAdapter;

    private List<PracticeTeamBean> mDataList = new ArrayList<>();
    private List<PracticeTeamBean> indexList = new ArrayList<>();

    private int page = 1;

    private int searchPage = 1;

    private boolean isSearchModel = false;

    private String keyword = "";

    private String volId;
    private String instId;
    private String streetId;
    private boolean isStreet = false;
    private boolean isMine = false;
    private int volStatus;

    public void setVolStatus(int volStatus) {
        this.volStatus = volStatus;
    }

    public void setVolId(String volId) {
        this.volId = volId;
    }

    public void setInstId(String instId) {
        this.instId = instId;
    }

    public void setStreetId(String streetId) {
        this.streetId = streetId;
    }

    public void setStreet(boolean street) {
        isStreet = street;
    }

    public void setMine(boolean mine) {
        isMine = mine;
    }

    @Override
    public void initImmersionBar() {
        super.initImmersionBar();
        ImmersionBar.with(this)
                .statusBarDarkFont(true,0.2f)
                .statusBarColor(R.color.white)
                .fitsSystemWindows(true)
                .init();
    }

    public static PracticeTeamListFragment newInstance(String instId, String volId, int volStatus, String streetId, boolean isStreet, boolean isMine) {
        PracticeTeamListFragment fragment = new PracticeTeamListFragment();
        fragment.setInstId(instId);
        fragment.setVolId(volId);
        fragment.setVolStatus(volStatus);
        fragment.setStreetId(streetId);
        fragment.setStreet(isStreet);
        fragment.setMine(isMine);
        return fragment;
    }

    @Override
    protected View createView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.practice_fragment_team_list, null);
    }

    @Override
    protected void create() {
        loadMask.setStatus(LoadingLayout.Loading);
        BusFactory.getBus().register(this);
        mPresenter = new PracticeTeamListPresenter(this);

        if (isMine) {
            refresh.setEnableLoadMore(false);
        } else {
            refresh.setEnableLoadMore(true);
        }

        refresh.setRefreshHeader(new MaterialHeader(getContext()));
        refresh.setRefreshFooter(new ClassicsFooter(getContext()));


        if (isStreet) {
            searchLayout.setVisibility(View.GONE);
        } else {
            if (isMine) {
                searchLayout.setVisibility(View.GONE);
            } else {
                searchLayout.setVisibility(View.VISIBLE);
            }
        }


        recycleView.setLayoutManager(new LinearLayoutManager(getContext()));

        recycleView.setAdapter(commonAdapter = new CommonAdapter<PracticeTeamBean>(getContext(), R.layout.practice_item_team_list, mDataList) {
            @Override
            protected void convert(ViewHolder holder, PracticeTeamBean bean, int position) {
                List<CountBean> countBeanList = new ArrayList<>();
                holder.setText(R.id.title, bean.getName());
                holder.setText(R.id.organization, "主管单位：" + bean.getStreetName());
                if (StringUtils.isNotEmpty(bean.getTypeName())) {
                    holder.setVisible(R.id.service_type, true);
                    holder.setText(R.id.service_type, "服务类别：" + bean.getTypeName());
                } else {
                    holder.setVisible(R.id.service_type, false);
                }

                if (StringUtils.isNotEmpty(bean.getContactName())) {
                    holder.setVisible(R.id.name, true);
                    holder.setText(R.id.name, "负责人：" + bean.getContactName());
                } else {
                    holder.setVisible(R.id.name, false);
                }

                if (StringUtils.isNotEmpty(bean.getContactPhone())) {
                    holder.setVisible(R.id.contact, true);
                    holder.setText(R.id.contact, "联系方式：" + bean.getContactPhone());
                } else {
                    holder.setVisible(R.id.contact, false);
                }

                countBeanList.add(new CountBean(bean.getVolNums(), "志愿者(人)"));
                countBeanList.add(new CountBean(bean.getActNums(), "服务项目(个)"));
                countBeanList.add(new CountBean(bean.getActTimes(), "服务时长(小时)"));
                countBeanList.add(new CountBean(bean.getActScore(), "爱心积分(个)"));

                RecyclerView recyclerView = holder.getView(R.id.count_rv);
                recyclerView.setLayoutManager(new GridLayoutManager(getContext(), 4));
                recyclerView.setAdapter(new CommonAdapter<CountBean>(getContext(), R.layout.practice_item_home_count, countBeanList) {
                    @Override
                    protected void convert(ViewHolder holder, CountBean bean, int position) {
                        if (position == 2) {
                            holder.setText(R.id.num, DateUtils.PracticeServiceTimeFormat(bean.getNum()));
                        } else {
                            holder.setText(R.id.num, StringUtils.transformNum(bean.getNum() + ""));
                        }

                        holder.setText(R.id.title, bean.getTitle());
                    }

                });
            }
        });

        if (volStatus == 1 || volStatus == 2) {
            bottomLayout.setVisibility(View.GONE);
        } else {
            bottomLayout.setVisibility(View.VISIBLE);
        }

        if (!isMine) {
            if (isStreet) {
                mPresenter.getList(page + "", streetId, isStreet);
            } else {
                mPresenter.getList(page + "", instId, isStreet);
            }
        } else {
            mPresenter.getVolTeamList(volId);
        }
    }

    @Override
    protected void setListener() {
        loadMask.setOnReloadListener(new LoadingLayout.OnReloadListener() {
            @Override
            public void onReload(View v) {
                if (!isMine) {
                    if (isSearchModel) {
                        searchPage = 1;
                        mPresenter.doSearch(keyword, searchPage + "");
                    } else {
                        page = 1;
                        if (isStreet) {
                            mPresenter.getList(page + "", streetId, isStreet);
                        } else {
                            mPresenter.getList(page + "", instId, isStreet);
                        }
                    }
                } else {
                    mPresenter.getVolTeamList(volId);
                }
            }
        });

        refresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                if (isSearchModel) {
                    searchPage = 1;
                    mPresenter.doSearch(keyword, searchPage + "");
                } else {
                    if (!isMine) {
                        page = 1;
                        if (isStreet) {
                            mPresenter.getList(page + "", streetId, isStreet);
                        } else {
                            mPresenter.getList(page + "", instId, isStreet);
                        }
                    } else {
                        mPresenter.getVolTeamList(volId);
                    }
                }
            }
        });

        refresh.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                if (isSearchModel) {
                    mPresenter.doSearch(keyword, searchPage + "");
                } else {
                    if (isStreet) {
                        mPresenter.getList(page + "", streetId, isStreet);
                    } else {
                        mPresenter.getList(page + "", instId, isStreet);
                    }
                }
            }
        });

        commonAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {

                Bundle bundle = new Bundle();
                bundle.putBoolean("isMine", isMine);
                bundle.putString("instId", instId);
                bundle.putString("volId", volId);
                bundle.putString("orgId", mDataList.get(position).getId() + "");
                RouterManager.router(ARouterPathConstant.PRACTICE_TEAM_DETAIL, bundle);

            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                return false;
            }
        });

        searchTxt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                keyword = s.toString();
                if (StringUtils.isNotEmpty(s.toString()) && s.toString().trim().length() > 0) {
                    searchBtn.setText("搜索");
                } else {
                    searchBtn.setText("取消");
                }
            }
        });

        searchTxt.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {//按下搜索
                    keyword = searchTxt.getText().toString();
                    searchPage = 1;
                    mPresenter.doSearch(keyword, searchPage + "");
                    hideInput();
                }
                return false;//返回true，保留软键盘。false，隐藏软键盘
            }

        });
    }

    @OnClick({R2.id.become_btn, R2.id.search_btn, R2.id.search_delete})
    public void onViewClicked(View view) {
        int id = view.getId();
        if (id == R.id.become_btn) {
            CommonUtils.getInstance().isLogin(new UserService.LoginCallBack() {
                @Override
                public void login(boolean isLogin) {
                    if (isLogin) {
                        Bundle bundle = new Bundle();
                        bundle.putBoolean("isVolunteer", true);
                        bundle.putString("instId", instId);
                        bundle.putString("id", "");
                        RouterManager.router(ARouterPathConstant.PRACTICE_VOLUNTEER_SIGN, bundle);

                    } else {
                        showToast("尚未登录或登录失效！");

                        RouterManager.routerLogin(getContext(), 0);
                    }
                }

                @Override
                public void error(String s) {

                }
            });

        } else if (id == R.id.search_btn) {
            if (searchBtn.getText().toString().equals("搜索")) {
                hideInput();
                if (StringUtils.isNotEmpty(keyword)) {
                    isSearchModel = true;
                    searchPage = 1;
                    mPresenter.doSearch(keyword, searchPage + "");
                } else {
                    showToast("搜索内容不能为空！", 4);
                }
            } else {
                if (indexList != null && indexList.size() > 0) {
                    loadMask.setStatus(LoadingLayout.Success);
                }
                isSearchModel = false;
                searchPage = 1;
                mDataList.clear();
                mDataList.addAll(indexList);
                commonAdapter.notifyDataSetChanged();
            }
        } else if (id == R.id.search_delete) {
            searchTxt.setText("");
        }
    }

    @Override
    protected void onFirstVisible() {

    }

    @Override
    protected void onVisible() {

    }

    @Override
    protected void onHide() {

    }

    @Override
    public void setList(List<PracticeTeamBean> beanList, boolean isMore) {
        loadMask.setStatus(LoadingLayout.Success);
        loadMask.setReloadButtonText("点击重试~");
        indexList.clear();
        if (isMore) {
            refresh.finishLoadMore();
        } else {
            refresh.finishRefresh();
            mDataList.clear();
        }
        page++;
        mDataList.addAll(beanList);
        indexList.addAll(mDataList);
        commonAdapter.notifyDataSetChanged();
    }

    @Override
    public void setSearchList(List<PracticeTeamBean> beanList, boolean isMore) {
        loadMask.setStatus(LoadingLayout.Success);
        loadMask.setReloadButtonText("点击重试~");
        if (isMore) {
            refresh.finishLoadMore();
        } else {
            refresh.finishRefresh();
            mDataList.clear();
        }
        searchPage++;
        mDataList.addAll(beanList);
        commonAdapter.notifyDataSetChanged();
    }

    @Override
    public void setIsVolunteer(PracticeIsVolunteerBean bean) {
        if (bean != null) {
            if (bean.getVolId() == 0) {
                bottomLayout.setVisibility(View.VISIBLE);
            } else {
                switch (bean.getStatus()) {
                    case "PASS":
                    case "NOT_VERIFY":
                        bottomLayout.setVisibility(View.GONE);
                        break;
                    case "NOT_PASS":
                    case "DEL":
                        bottomLayout.setVisibility(View.VISIBLE);
                        break;
                    default:
                        break;
                }
            }
        } else {
            bottomLayout.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void setError(String msg, boolean isMore) {
        if (isMore) {
            refresh.finishLoadMore();
            if (!NetUtil.isNetworkAvalible(getContext())) {
                showToast("网络异常，请检查您的网络！", 4);
            } else if (msg.contains("暂无")) {
                showToast("暂无更多队伍！", 4);
            } else {
                showToast(msg, 4);
            }
        } else {
            refresh.finishRefresh();
            loadMask.setStatus(LoadingLayout.Error);
            loadMask.setReloadButtonText("点击重试~");
            if (!NetUtil.isNetworkAvalible(getContext())) {
                loadMask.setErrorImage(R.drawable.error_network);
                loadMask.setErrorText("网络异常，请检查您的网络！");
            } else if (msg.contains("暂无")) {
                loadMask.setErrorImage(R.drawable.empty_content);
                loadMask.setErrorText(msg);
            } else {
                loadMask.setErrorImage(R.drawable.error_content);
                loadMask.setErrorText(msg);
            }
        }
    }

    class CountBean implements Serializable {
        private int num;
        private String title;

        CountBean(int num, String title) {
            this.num = num;
            this.title = title;
        }

        public int getNum() {
            return num;
        }

        public void setNum(int num) {
            this.num = num;
        }

        public String getTitle() {
            return title;
        }

        public void setTitle(String title) {
            this.title = title;
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void refresh(Event.PracticeActRefresh event) {
        if (event != null) {
            bottomLayout.setVisibility(View.GONE);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void loginMessage(Event.LoginMessage event) {
        if (event != null) {
            if (event.isLogin()) {
                //登录
                String userName = CommonUtils.getInstance().getUserName();
                mPresenter.getIsVolunteer(userName);
            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        BusFactory.getBus().unregister(this);
    }
}
